package com.tf.pemporaryfood.service.serviceImpl;

import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.digest.MD5;
import com.tf.pemporaryfood.domain.VO.UserVO;
import com.tf.pemporaryfood.domain.entity.User;
import com.tf.pemporaryfood.mapper.UserMapper;
import com.tf.pemporaryfood.service.UserService;
import com.tf.pemporaryfood.util.SnowFlakeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * TODO
 *
 * @author Young genius
 * @date 2021年05月28日 18:26
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    private String[] userIcons = {
            "http://m.qpic.cn/psc?/V51qFftk1j3erE0aml7v3BpS353gy4GX/45NBuzDIW489QBoVep5mcfOslXAXxQDd5I0vbGmRJLVeUdljuy60qnQeQTCxdQ2TpsFJJ7gVPTkEqdft9LeHehuCQmCqIajn9i5P3uGa0yo!/b&bo=agJqAgAAAAABFzA!&rf=viewer_4",
            "http://m.qpic.cn/psc?/V51qFftk1j3erE0aml7v3BpS353gy4GX/45NBuzDIW489QBoVep5mcfr1dnbgiss1H6aid5sfS97UvD85Nbi4g1MCbxK8wKlKCTHv5*KffUcpt7UfJ0UMrDCQzwghsXX0mNNusZYrrPQ!/b&bo=9AH0AQAAAAABFzA!&rf=viewer_4",
            "http://m.qpic.cn/psc?/V51qFftk1j3erE0aml7v3BpS353gy4GX/45NBuzDIW489QBoVep5mcfr1dnbgiss1H6aid5sfS94stodlgMHAQTynZUvqXKRgUPBwmo7llFmp.P5JdZkc*urseiAF71IhemwciDr1M2E!/b&bo=9AH0AQAAAAABFzA!&rf=viewer_4",
            "http://m.qpic.cn/psc?/V51qFftk1j3erE0aml7v3BpS353gy4GX/45NBuzDIW489QBoVep5mcdalWI5zN5fDU*u.kgZ4JVR9oWCToSd0n3rFJCxMa0qLq.DZuHorN0FSLhizSaI.wa6LcIA4umlIPdDhmHzYqY0!/b&bo=9AH0AQAAAAABFzA!&rf=viewer_4",
            "http://m.qpic.cn/psc?/V51qFftk1j3erE0aml7v3BpS353gy4GX/45NBuzDIW489QBoVep5mcdalWI5zN5fDU*u.kgZ4JVTO3O4nz3aCtBS8Li*jjV0Ckl11spgNWpgnakWq*HVR6ggDynFLnIi6P44cP*cIfy8!/b&bo=9AH0AQAAAAABFzA!&rf=viewer_4"
    };
    /**
     * 通过userId 查询user信息
     *
     * @param id userId
     * @return user信息
     */
    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    /**
     * 添加用户
     *
     * @return 返回数字1则添加成功 0为失败
     */
    @Override
    public int addUser(UserVO userVO) {
        User convert = Convert.convert(User.class, userVO);
        //给新用户设置id
        convert.setUserId(SnowFlakeUtils.nextId());
        //获取原来的密码 加密
        String oldPassword = userVO.getUserPassword();
        String newPassword = MD5.create().digestHex16(oldPassword);
        convert.setUserPassword(newPassword);
        //随机一个头像
        convert.setUserIcon(userIcons[new Random().nextInt(userIcons.length)]);
        System.out.println(convert);
        return userMapper.addUser(convert);
    }

    /**
     * 根据手机号和密码查询user
     *
     * @param phone    手机号
     * @param password 密码
     * @return user对象
     */
    @Override
    public User findUserByPhoneAndPassword(String phone, String password) {
        String newPassword=MD5.create().digestHex16(password);
        return userMapper.findUserByPhoneAndPassword(phone, newPassword);
    }
}
